package com.nio.netty.protocoltcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import static io.netty.util.CharsetUtil.UTF_8;

public class MyClientHandler extends SimpleChannelInboundHandler<MessageProtocol> {
    private int count;
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {

        int len = msg.getLen();
        byte[] content = msg.getContent();
        System.out.println("客户端接收到的消息长度："+len);
        System.out.println("客户端接收到的消息内容："+new String(content,UTF_8));
        System.out.println("客户端接受消息数量："+(++this.count));

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        /*使用客户端发送10条数据， "天气冷，吃火锅！"*/

        for (int i=0;i<5;i++){
            String msg="天气冷，吃火锅！";
            byte[] content   = msg.getBytes(UTF_8);
            int length = msg.getBytes(UTF_8).length;
            /*创建协议包*/
            MessageProtocol messageProtocol = new MessageProtocol();
            messageProtocol.setLen(length);
            messageProtocol.setContent(content);
            ctx.writeAndFlush(messageProtocol);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
